import { API_URI } from '../constants/index';


export async function streamingApiCall(
    endpoint: string, token: string, body: object, chunkCallback: Function
) {
    const requestHeaders: HeadersInit = new Headers();
    requestHeaders.set('Content-Type', 'application/json');
    requestHeaders.set('Authorization', `Bearer ${token}`);
    const response = await fetch(
        API_URI + endpoint,
        {
            method: 'POST',
            headers: requestHeaders,
            body: JSON.stringify(body),
        }
    );
    async function processStream(stream: ReadableStream<Uint8Array>): Promise<object> {
        let result = '';
        const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
        while (true) {
            const { done, value } = await reader.read();
            if (done) {
                break;
            }
            result += value;
            try {
            const data = JSON.parse(value.replace(/,\n$/, ''));
                chunkCallback(data);
            } catch (e) {
                console.warn('corrupted chunk:', value, 'parsing error:', e);
            }
        }
        console.log(result);
        const list = JSON.parse(result);
        return list[list.length - 1];
    }
    const result = await processStream(response.body!);
    return result;
}